// pages/shop-cart/shopcard.js
const app = getApp()
const http = require('../../utils/httpUtils.js')
Page({
    /**
     * 页面的初始数据
     */
    data: {
        navbarData: {
            showCapsule: 1, //是否显示左上角图标
            title: '购物车' //导航栏 中间的标题
        },
        height: app.globalData.height * 2 + 20,
        // ip: app.globalData.host,
        goodsList: {
            saveHidden: true,
            totalPrice: 0,
            allSelect: false,
            noSelect: true,
            list: []
        },
        resList: [],
        delBtnWidth: 300 //删除按钮宽度单位（rpx）
    },
    //获取元素自适应后的实际宽度
    getEleWidth(w) {
        var real = 0;
        try {
            var res = wx.getSystemInfoSync().windowWidth
            var scale = (750 / 2) / (w / 2) //以宽度750px设计稿做宽度的自适应
            real = Math.floor(res / scale)
            return real
        } catch (e) {
            return false
        }
    },
    initEleWidth() {
        var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
        this.setData({
            delBtnWidth: delBtnWidth
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        this.initEleWidth()
        this.getData()
    },
    //请求后台购物车数据
    getData(Type) {
        let shopList = Array()
        // 获取购物车数据
        http._headerGet('/api/Cart/cart_list', {
            'c_client': 'weixinSmall'
        }, res => {
            if (res.data.code == 1 && res.data.data != '') {
                shopList = res.data.data;
                shopList.forEach(item => {
                    // console.log(item.shop)
                    item.shop.cart_goods.forEach(res => {
                        // console.log(res)
                        res.active = false
                        res.left = ''
                    })
                })
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), false, this.noSelect(), shopList)
                wx.stopPullDownRefresh()
            }
        }, '', comp => {
            wx.stopPullDownRefresh()
        })
    },
    /**
     * 当购物车为空时，去首页
     */
    toIndexPage() {
        wx.switchTab({
            url: "/pages/tabBar/specialty/specialty"
        });
    },
    /**
     * 触摸动作开始
     */
    touchS(e) {
        if (e.touches.length == 1) {
            this.setData({
                startX: e.touches[0].clientX
            })
        }
    },
    /**
     * 触摸动作进行中
     */
    touchM(e) {
        let list = this.data.goodsList.list;
        let index = e.currentTarget.dataset.index;
        if (e.touches.length == 1) {
            let moveX = e.touches[0].clientX
            let disX = this.data.startX - moveX
            let delBtnWidth = this.data.delBtnWidth
            let left = ""
            if (disX == 0 || disX < 0) { //如果移动距离小于等于0，container位置不变
                left = "margin-left:0rpx"
            } else if (disX > 0) { //移动距离大于0，container left值等于手指移动距离
                left = "margin-left:-" + disX + "rpx"
                if (disX >= delBtnWidth) {
                    left = "margin-left:-" + delBtnWidth + "rpx";
                }
            }
            for (let i = 0; i < list.length; i++) {
                let curItem = list[i].shop.cart_goods;
                for (let k = 0; k < curItem.length; k++) {
                    if (curItem[k].sku_id == index)
                        curItem[k].left = left
                }
            }
            this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list)
        }
    },
    /**
     * 触摸动作结束
     */
    touchE(e) {
        let index = e.currentTarget.dataset.index;
        if (e.changedTouches.length == 1) {
            let endX = e.changedTouches[0].clientX;
            let disX = this.data.startX - endX;
            let delBtnWidth = this.data.delBtnWidth;
            //如果距离小于删除按钮的1/2，不显示删除按钮
            let left = disX >= delBtnWidth ? "margin-left:-" + delBtnWidth + "rpx" : "margin-left:0px";
            let list = this.data.goodsList.list;
            for (let i = 0; i < list.length; i++) {
                let curItem = list[i].shop.cart_goods;
                for (let k = 0; k < curItem.length; k++) {
                    if (curItem[k].sku_id == index)
                        curItem[k].left = left
                }
            }
            this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
        }
    },
    /**
     * 删除单个商品（左滑删除）
     */
    delItem(e) {
        let data = e.currentTarget.dataset
        let list = this.data.goodsList.list
        list[data.idx].shop.cart_goods.splice(data.index, 1)
        if (list[data.idx].shop.cart_goods.length == 0)
            list.splice(data.idx, 1)
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
        http._headerPost('/api/Cart/del_cart', {
            'c_client': 'weixinSmall', //客户端
            'cart_id': data.cardid
        }, res => {
            if (res.data.code == 1) {
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
            }
        })
    },
    /**
     * 点击选择状态
     */
    selectTap(e) {
        let index = e.currentTarget.dataset.index;
        let list = this.data.goodsList.list;
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].sku_id == index) {
                    curItem[k].active = !curItem[k].active
                }
            }
        }
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    /**
     * 计算选中商品价格
     */
    totalPrice: function() {
        let list = this.data.goodsList.list;
        let total = 0;
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].active) {
                    total += parseFloat(curItem[k].price) * curItem[k].num
                }
            }
        }
        total = this.getFloatStr(total.toFixed(2)) //js浮点计算bug，取两位小数精度
        return total;
    },
    // 强制保留两位小数
    getFloatStr(num) {
        if (!/\./.test(num)) //为整数字符串在末尾添加.00  
            num += '.00'
        return num
    },
    /**
     * 判断是否全部选中
     */
    allSelect: function() {
        let list = this.data.goodsList.list;
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (!curItem[k].active) {
                    return false
                }
            }
        }
        return true;
    },
    /**
     * 判断是否全部没有选中
     */
    noSelect: function() {
        let list = this.data.goodsList.list;
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].active) {
                    return false
                }
            }
        }
        return true
    },
    /**
     * 设置购物车数据以及状态
     */
    setGoodsList(saveHidden, total, allSelect, noSelect, list) {
        this.setData({
            goodsList: {
                saveHidden: saveHidden,
                totalPrice: total,
                allSelect: allSelect,
                noSelect: noSelect,
                list: list
            }
        });
    },
    /**
     * 全部选中，或者全部取消选中
     */
    bindAllSelect() {
        let currentAllSelect = this.data.goodsList.allSelect;
        let list = this.data.goodsList.list;
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].active == currentAllSelect) {
                    curItem[k].active = !currentAllSelect
                }
            }
        }
        this.setGoodsList(this.getSaveHide(), this.totalPrice(), !currentAllSelect, this.noSelect(), list);
    },
    /**
     * 加减按钮
     */
    numBtnTap: function(e) {
        let data = e.currentTarget.dataset
        let list = this.data.goodsList.list
        if (data.type == 'add') {
            list[data.idx].shop.cart_goods[data.index].num++
        } else if (list[data.idx].shop.cart_goods[data.index].num > 1) {
            list[data.idx].shop.cart_goods[data.index].num--
        } else {}

        let upData = {}
        upData.cart_id = list[data.idx].shop.cart_goods[data.index].id
        upData.num = 1
        upData.c_client = "weixinSmall"
        upData.type = data.type

        http._headerPost('/api/Cart/alter_cart', upData, res => {
            if (res.data.code == 1) {
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list)
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    /**
     * 编辑按钮
     */
    editTap: function() {
        var list = this.data.goodsList.list;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            curItem.active = false;
        }
        this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    /**
     * 完成按钮
     */
    saveTap: function() {
        var list = this.data.goodsList.list;
        for (var i = 0; i < list.length; i++) {
            var curItem = list[i];
            curItem.active = true;
        }
        this.setGoodsList(!this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    },
    /**
     * 获得编辑状态还是非编辑状态
     */
    getSaveHide() {
        let saveHidden = this.data.goodsList.saveHidden;
        return saveHidden;
    },
    /**
     * 删除选中商品
     */
    deleteSelected() {
        let list = this.data.goodsList.list;
        let ids = ''
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].active == true) {
                    ids += curItem[k].id + ','
                    curItem.splice(k, 1)
                    k--
                    if (curItem.length == 0) {
                        list.splice(i, 1)
                        i--
                    }
                }
            }
        }
        http._headerPost('/index/Cart/delete', {
            ids: ids.substring(0, ids.length - 1)
        }, res => {
            if (res.data.code == 1) {
                this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list)
                wx.showToast({
                    title: res.data.msg,
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    /**
     * 结算购物车选中商品
     */
    toPayOrder() {
        let list = this.data.goodsList.list;
        let ids = ''
        for (let i = 0; i < list.length; i++) {
            let curItem = list[i].shop.cart_goods;
            for (let k = 0; k < curItem.length; k++) {
                if (curItem[k].active == true) {
                    ids += curItem[k].id + ','
                }
            }
        }
        ids = ids.substring(0, ids.length - 1)
        let data = {}
        data.type = 'cart'
        data.cart_id = ids
        data.c_client = "weixinSmall";
        data.v = "1.1.0";
        wx.navigateTo({
            url: '../public/confirm-order/index?data=' + JSON.stringify(data)
        })
    },
    navigateToPayOrder(data) {
        wx.navigateTo({
            url: "/pages/second/to-pay/topay?data=" + JSON.stringify(data) + "&type=card"
        })
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getData()
    }
})